package com.yky.config;

import com.yky.filter.RepeatableFilter;
import com.yky.filter.RequestDecryptionFilter;
import com.yky.filter.ResponseEncryptFilter;
import com.yky.filter.XssFilter;
import com.yky.utils.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Filter;

/**
 * 业务聚合
 *
 * @version [V2.0]
 * @package com.yky.config;
 * @description:[用一句话描述该文件做什么]
 * @author: [zhuben]
 * @date: [2024-02-26 18:54]
 * @copyright: 2024 echovin.com
 */
@Configuration
public class FilterConfig {
    /**
     * 是否开启xss过滤
     */
    @Value("${yky.xss.enabled}")
    private String enabled;
    /**
     * 排除的url
     */
    @Value("${yky.xss.excludes}")
    private String excludes;
    /**
     * 校验的url
     */
    @Value("${yky.xss.urlPatterns}")
    private String urlPatterns;

    @Bean
    public FilterRegistrationBean<XssFilter> xssFilter(){
        FilterRegistrationBean<XssFilter> registration = new FilterRegistrationBean<>();
        registration.setDispatcherTypes(DispatcherType.REQUEST);
        registration.setFilter(new XssFilter());
        registration.addUrlPatterns(StringUtils.split(urlPatterns, ","));
        registration.setName("xssFilter");
        registration.setOrder(FilterRegistrationBean.LOWEST_PRECEDENCE);
        Map<String, String> initParameters = new HashMap<String, String>();
        initParameters.put("excludes", excludes);
        initParameters.put("enabled", enabled);
        registration.setInitParameters(initParameters);
        return registration;
    }

    @Bean
    public FilterRegistrationBean<RepeatableFilter> repeatableFilter(){
        FilterRegistrationBean<RepeatableFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new RepeatableFilter());
        registration.addUrlPatterns("/*");
        registration.setName("repeatableFilter");
        registration.setOrder(FilterRegistrationBean.LOWEST_PRECEDENCE);
        return registration;
    }
}
